<?php
namespace Partner\Controller;

use Utuo\BackgroundController;

class PartnerProductController extends BackgroundController {

	public function _initialize() {
		$this->setControllerTitle('商城信息设置');
		$this->setActionTitle(array(
				'index' => '商城信息',
				'url' => '商城地址',
		));
		$this->setActionNav('index,url');
	}
	
	/**
	 * 合作商商城基本配置
	 */
	public function indexAction() {
		$dProduct = D('PartnerProduct');
		$partnerProduct = $dProduct->find($this->aid);
		if (!$partnerProduct) {
			$data = array(
					'id' => $this->aid,
					'pid' => $this->aid,
					'name' => $this->aname
			);
			if (!$dProduct->add($data)) {
				$this->error('添加商城信息失败');
			}
			$partnerProduct = $dProduct->find($this->aid);
		}
		$partnerProduct['percent'] = explode(':', $partnerProduct['percent']);
		array_sum( $partnerProduct['percent'] ) or $partnerProduct['percent'][0] = 10;
		$partnerProduct['status'] = $this->getRadio('status', $dProduct->status, $partnerProduct['status']);
		$this->assign('partnerProduct', $partnerProduct);
		$this->display('save');
	}
	
	/**
	 * 首页地址
	 */
	public function urlAction() {
		$partnerProduct = M('PartnerProduct')->find($this->aid);
		$partnerProduct['url'] = url('Home', 'Shop', 'index', "pid={$this->aid}", true);
		$this->assign('partnerProduct', $partnerProduct);
		$this->display();
	}
	
	/**
	 * 保存商品
	 */
	public function saveAction() {
		$dProduct = D('PartnerProduct');
		if ($dProduct->create()) {
			$dProduct->pid = $this->aid;
			if (empty($dProduct->id)) {
				C('TOKEN_ON', true);
				$dProduct->id = $dProduct->pid;
				$dProduct->add() !== false && $this->ajaxSuccess();
			} else {
				/* 配置保存 */
				unset($dProduct->pid);
				$newProduct = clone $dProduct;
				$product = $newProduct->find( $dProduct->id );
				/* 保存 */
				$dProduct->save() !== false && $this->ajaxSuccess();
			}
		}
		$this->ajaxError();
	}
	
}